package com.opgea.tutor.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.AjaxBehaviorEvent;

import org.apache.log4j.Logger;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opgea.tutor.TutorException;
import com.opgea.tutor.domain.model.PrimeFacesFileUploadBean;
import com.opgea.tutor.service.TutorService;
import com.opgea.tutor.util.ApplicationUtil;
import com.opgea.tutor.util.FacesUtil;
import com.opgea.tutor.util.PageConstants;
import com.opgea.tutor.web.dto.AddressDTO;
import com.opgea.tutor.web.dto.EducationDTO;
import com.opgea.tutor.web.dto.EmailDTO;
import com.opgea.tutor.web.dto.LocationDTO;
import com.opgea.tutor.web.dto.PhoneDTO;
import com.opgea.tutor.web.dto.SpecializationDTO;
import com.opgea.tutor.web.dto.TutorDTO;

@ManagedBean(name = "tutorController")
@RequestScoped
@Component
@Scope(value = "request")
public class TutorController {

    private Logger logger = Logger.getLogger(TutorController.class);

    @Autowired
    private TutorService tutorService;

    private TutorDTO tutorDTO = new TutorDTO();
    private AddressDTO addressDTO = new AddressDTO();
    private PhoneDTO phoneDTO = new PhoneDTO();
    private EmailDTO emailDTO = new EmailDTO();
    private SpecializationDTO specializationDTO = new SpecializationDTO();
    private LocationDTO locationDTO = new LocationDTO();
    private EducationDTO educationDTO = new EducationDTO();

    private List<AddressDTO> addressDTOList = new ArrayList<AddressDTO>();
    private List<PhoneDTO> phoneDTOList = new ArrayList<PhoneDTO>();
    private List<EmailDTO> emailDTOList = new ArrayList<EmailDTO>();
    private List<SpecializationDTO> specializationDTOList = new ArrayList<SpecializationDTO>();
    private List<EducationDTO> educationDTOList = new ArrayList<EducationDTO>();

    private boolean renderForm;
    private UploadedFile file;

    @PostConstruct
    public void init() {
	if (FacesUtil.getHttpSession() != null
		&& FacesUtil.getSessionUserDataObject().getLoginIdPrimaryKey() != null) {
	    long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();

	    try {
		phoneDTOList = tutorService.findPhoneNumbers(tutorId);
		emailDTOList = tutorService.findEmailIds(tutorId);
		specializationDTOList = tutorService
			.findSpecializations(tutorId);
		educationDTOList = tutorService.findEducations(tutorId);
		if (!FacesUtil.getPageName().equalsIgnoreCase(
			PageConstants.NEW_PAGE)) {
		    tutorDTO = tutorService.findByLoginId(tutorId);
		    addressDTO = tutorService.findAddress(tutorId);
		    locationDTO = tutorService.findLocation(tutorId);
		    if (phoneDTOList != null && phoneDTOList.size() > 0) {
			phoneDTO = phoneDTOList.get(0);
		    }
		    if (emailDTOList != null && emailDTOList.size() > 0) {
			emailDTO = emailDTOList.get(0);
		    }
		    if (specializationDTOList != null
			    && specializationDTOList.size() > 0) {
			specializationDTO = specializationDTOList.get(0);
		    }
		    if (educationDTOList != null && educationDTOList.size() > 0) {
			educationDTO = educationDTOList.get(0);
		    }
		}
	    } catch (TutorException e) {
		FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
			e.getMessage(), null);
	    }
	}
	System.out.println("Servlet Path: " + FacesUtil.getPageName());
    }

    public TutorDTO getTutorDTO() {
	return tutorDTO;
    }

    public void setTutorDTO(TutorDTO tutorDTO) {
	this.tutorDTO = tutorDTO;
    }

    public AddressDTO getAddressDTO() {
	return addressDTO;
    }

    public void setAddressDTO(AddressDTO addressDTO) {
	this.addressDTO = addressDTO;
    }

    public List<AddressDTO> getAddressDTOList() {
	return addressDTOList;
    }

    public void setAddressDTOList(List<AddressDTO> addressDTOList) {
	this.addressDTOList = addressDTOList;
    }

    public PhoneDTO getPhoneDTO() {
	return phoneDTO;
    }

    public void setPhoneDTO(PhoneDTO phoneDTO) {
	this.phoneDTO = phoneDTO;
    }

    public EmailDTO getEmailDTO() {
	return emailDTO;
    }

    public void setEmailDTO(EmailDTO emailDTO) {
	this.emailDTO = emailDTO;
    }

    public LocationDTO getLocationDTO() {
	return locationDTO;
    }

    public void setLocationDTO(LocationDTO locationDTO) {
	this.locationDTO = locationDTO;
    }

    public List<PhoneDTO> getPhoneDTOList() {
	return phoneDTOList;
    }

    public void setPhoneDTOList(List<PhoneDTO> phoneDTOList) {
	this.phoneDTOList = phoneDTOList;
    }

    public List<EmailDTO> getEmailDTOList() {
	return emailDTOList;
    }

    public void setEmailDTOList(List<EmailDTO> emailDTOList) {
	this.emailDTOList = emailDTOList;
    }

    public SpecializationDTO getSpecializationDTO() {
	return specializationDTO;
    }

    public void setSpecializationDTO(SpecializationDTO specializationDTO) {
	this.specializationDTO = specializationDTO;
    }

    public EducationDTO getEducationDTO() {
	return educationDTO;
    }

    public void setEducationDTO(EducationDTO educationDTO) {
	this.educationDTO = educationDTO;
    }

    public List<SpecializationDTO> getSpecializationDTOList() {
	return specializationDTOList;
    }

    public void setSpecializationDTOList(
	    List<SpecializationDTO> specializationDTOList) {
	this.specializationDTOList = specializationDTOList;
    }

    public List<EducationDTO> getEducationDTOList() {
	return educationDTOList;
    }

    public void setEducationDTOList(List<EducationDTO> educationDTOList) {
	this.educationDTOList = educationDTOList;
    }

    public boolean isRenderForm() {
	return renderForm;
    }

    public void setRenderForm(boolean renderForm) {
	this.renderForm = renderForm;
    }

    public UploadedFile getFile() {
	return file;
    }

    public void setFile(UploadedFile file) {
	this.file = file;
    }

    public String updatePersonalDetails() {
	logger.info("updatePersonalDetails >> " + tutorDTO);
	Long loginIdPrimaryKey = FacesUtil.getLoginDTOFromSession().getId();
	long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	tutorDTO.setId(tutorId);
	tutorDTO.setLoginIdPrimaryKey(loginIdPrimaryKey);
	try {
	    tutorService.update(tutorDTO);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    tutorDTO.getFirstName()
			    + "\'s personal details saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}

	return "create.xhtml";
    }

    public String updateAddress() {
	logger.info("updateAddress >> " + addressDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updateAddress(tutorId, addressDTO);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Address saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public String updateLocation() {
	logger.info("updateLocation >> " + locationDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updateLocation(tutorId, locationDTO);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Location saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public String updatePhone() {
	logger.info("updatePhone >> " + phoneDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updatePhone(tutorId, phoneDTO);
	    phoneDTOList = tutorService.findPhoneNumbers(tutorId);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Phone saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public String updateEmail() {
	logger.info("updateEmail >> " + emailDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updateEmail(tutorId, emailDTO);
	    emailDTOList = tutorService.findEmailIds(tutorId);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Email saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public String updateSpecialization() {
	logger.info("updateSpecialization >> " + specializationDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updateSpecialization(tutorId, specializationDTO);
	    specializationDTOList = tutorService.findSpecializations(tutorId);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Specialization saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public String updateEducation() {
	logger.info("updateEducation >> " + educationDTO);
	Long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	try {
	    tutorService.updateEducation(tutorId, educationDTO);
	    educationDTOList = tutorService.findEducations(tutorId);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    "Education saved successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
		    e.getMessage(), null);
	}
	return "create.xhtml";
    }

    public void editEducationAjax(AjaxBehaviorEvent ae) {
	logger.info("editEducation >> " + educationDTO);
	if (FacesUtil.getRequestParameter("id") != null) {
	    long id = Long.parseLong((String) FacesUtil
		    .getRequestParameter("id"));
	    EducationDTO eDTO = new EducationDTO();
	    eDTO.setId(id);
	    educationDTO = (EducationDTO) ApplicationUtil.findObject(eDTO,
		    educationDTOList);
	}
    }

    public String editEducation() {
	logger.info("editEducation >> " + educationDTO);
	if (FacesUtil.getRequestParameter("id") != null) {
	    long id = Long.parseLong((String) FacesUtil
		    .getRequestParameter("id"));
	    EducationDTO eDTO = new EducationDTO();
	    eDTO.setId(id);
	    eDTO = (EducationDTO) ApplicationUtil.findObject(eDTO,
		    educationDTOList);
	    educationDTO = eDTO;
	}
	return "create.xhtml";
    }

    public void removeEducation(AjaxBehaviorEvent ae) {
	logger.info("removeEducation >> " + educationDTO);
	if (FacesUtil.getRequestParameter("id") != null) {
	    long tutorId = FacesUtil.getSessionUserDataObject().getPrimaryKey();
	    long educationDetailsId = Long.parseLong((String) FacesUtil
		    .getRequestParameter("id"));
	    try {
		tutorService.removeEducation(tutorId, educationDetailsId);
		educationDTOList = tutorService.findEducations(tutorId);
		FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
			"Education removed successfully!", null);
	    } catch (TutorException e) {
		FacesUtil.addMessage("messages", FacesMessage.SEVERITY_ERROR,
			e.getMessage(), null);
	    }

	}
    }

    public void uploadDocument(FileUploadEvent fe) {
	file = fe.getFile();
	PrimeFacesFileUploadBean pfFileUploadBean = new PrimeFacesFileUploadBean();
	pfFileUploadBean.setFile(file);
	try {
	    tutorService.uploadDocument(FacesUtil.getSessionUserDataObject()
		    .getPrimaryKey(), pfFileUploadBean);
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    file.getFileName() + ", uploaded successfully!", null);
	} catch (TutorException e) {
	    FacesUtil.addMessage("messages", FacesMessage.SEVERITY_INFO,
		    e.getMessage(), null);
	}
    }

    public void enableFormRendering(AjaxBehaviorEvent ae) {
	this.renderForm = true;
    }

    public void disableFormRendring(AjaxBehaviorEvent ae) {
	this.renderForm = false;
    }
}
